package com.tanhua.dubbo.api.impl;

import com.tanhua.domain.mongo.RemainingTimes;
import com.tanhua.domain.mongo.Voice;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VoiceApi;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.http.ResponseEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


@Service(timeout = 10000)//超时过一秒，连接一次，失败重连两次
public class VoiceApiImpl implements VoiceApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Voice voice) {
        mongoTemplate.save(voice);
    }

    @Override
    public void setVoice() {
        Query query = new Query();
        Update update = new Update();
        update.set("remainingTimes", 10);
        //检查是不是所以的数据都设置成10
        mongoTemplate.updateMulti(query, update, RemainingTimes.class);
    }

    @Override
    public void delete(Voice voice) {
        mongoTemplate.remove(voice);
    }

    @Override
    public List<Voice> allVoice() {
        Query query = new Query();
        List<Voice> voiceList = mongoTemplate.find(query, Voice.class);
        return voiceList;
    }

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private VoiceApi voiceApi;

    @Override
    public Object queryVoice(Long userId) {
        //查voice表中的所含有的userId存在一个集合里面，然后随机取一个，然后删除自己的userId
        List<Voice> voiceList = voiceApi.allVoice();
        List<Voice> voiceListNotMine = new ArrayList<>();
        if (voiceList.size()==1&&voiceList.get(0).getUserId()==userId) {
            return null;
        }
        for (Voice voice : voiceList) {
            if (voice.getUserId() != userId) {
                voiceListNotMine.add(voice);
            }
        }
        Voice voice = voiceListNotMine.get(new Random().nextInt(voiceList.size()) + 1);//[0,100) [1,101)
/*        //可以使用redis查询的更加快 这里查询太慢了
        Integer allUserNum = userInfoApi.allUser();
        Integer userId2 = new Random().nextInt((int) (allUserNum)) + 1;//[0,99)  [1,100)

        while (userId2 == userId.intValue()) {
            userId2 = new Random().nextInt((int) (allUserNum)) + 1;
        }

        Query query = new Query(Criteria.where("userId").is(userId2));
        Voice voice = mongoTemplate.findOne(query, Voice.class);*/
        return voice;

    }
}
